﻿require('es6-promise').polyfill();
require('mmRouter');
var server = require('api');
var _alert = require('alert');
var _clear = require('clearForm');
// require('jquery');

var index = [];
avalon.config({
    debug: true
});


var header = '<div class="panel panel-default"><div class="panel-body"><div></div></div></div>';
var footer = '<div class="panel panel-default footer"><div class="panel-body">消防队管理版权所有</div></div>';


// index 模块入口
var root = avalon.define({
    $id: 'root',
    active: true,
    getRootFun: function () {
        avalon.log('Root|'+new Date());
    },


    //imgs
    logoImg : require('./img/login/logo.png'),
    op: require('./img/op.png'),
    org: require('./img/org.png'),
    send: require('./img/send.png'),
    team:  require('./img/team.png'),
    up:  require('./img/up.png'),

    needLogin: false,
    loginPage: '',
    headerPage: header,//头部页面
    footerPage: footer,//尾部页面
    currPath: '',//当前路径k
    currPage: '',//当前页面
    user:{
        id:'',
        token:'',
        userAccount: '',
        userType: '',
        groupId: '',
        userName: '',
        oldPwd: '',
        newPwd: '',
        repeatPwd: '',
        menuList: []
    //    ["yonghuguanli","keshileixingguanli","zuzhijigouguanli","jixiaoguangli", "zonghechaxun","renwuleixingguanli","renwuguanli"]
    },

    pwd:{
        old: false,
        re: false,
        new: false
    },

    //iconfont defined

    font: {
        eot: require('./font/iconfont.eot'),
        woff: require('./font/iconfont.woff'),
        ttf: require('./font/iconfont.ttf')
    },

    logout: function () {
      window.location.reload();
    },

    isShow: function (item) {

        var menuList = root.user.menuList.$model;

        if (menuList.length > 0 ){

            if (_.indexOf(index, item) > -1){
                return false;
            }

            if (_.indexOf(menuList, item) > -1){
                index.push(item);
                avalon.log(index);
                avalon.log(item + 'display');
                return true;
            }else {
                avalon.log(item + 'no display');
                return false;
            }

        }else{
            return false
        }
    },

    validate1: function () {
        if (root.user.oldPwd == ''){
            root.pwd.old = true;
        }else {
            root.pwd.old = false;
        }
    },

    validate2: function () {
        if (root.user.newPwd == ''){
            root.pwd.new = true
        }else{
            root.pwd.new = false
        }
    },

    validate3: function () {
        if (root.user.repeatPwd != root.user.newPwd){
            root.pwd.re = true
        }else{
            root.pwd.re = false
        }
    },

    changePwd: function () {

        var data = {
            userId:root.user.id,
            userToken:root.user.token,
            oldPassword:root.user.oldPwd,
            newPassword:root.user.newPwd
        };

        $.ajax({
            type:'put',
            url:server.changePwd,
            data:JSON.stringify(data),
            dataType:'json',
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .done(function (res) {
                var data = res.values;
                if (res.status == '9200'){
                    _alert('修改成功');
                    _clear($('#changePwdModal'));
                    $('#changePwdModal').modal('hide');
                }else{
                    _alert('修改失败: ' + res.description);
                }
            })
            .fail(function (res) {
                _alert('修改失败：网络错误，请刷新后重试！');
            })
    }
});


var states = {};

function addState(path, vm, html) {
    states[path] = {
        vm: vm,
        html: html
    }
}

// custom component ms-view
avalon.component('ms-view', {
    template: '<div ms-html="@page" class="ms-view"></div>',
    defaults: {
        page: '&nbsp;',
        path: 'no',
        onReady: function(e) {
            var path = e.vmodel.path;
            var state = states[path];
            avalon.vmodels[state.vm.$id] = state.vm;
            avalon.vmodels[state.vm.$id].init();
            setTimeout(function() {//必须等它扫描完这个template,才能替换
                e.vmodel.page = state.html
            },100)
        },
        onDispose: function(e) {
            var path = e.vmodel.path;
            var state = states[path];
            var vm = state.vm;
            var render = vm.render;
            render && render.dispose();
            delete avalon.vmodels[vm.$id]
        }
    }
});

function getPage(path) {
    path = path.slice(1);
    var html = '<xmp is="ms-view" class="view-container" ms-widget="{path:\'' + path + '\',page: @page}"><xmp>';
    return html
}

var pages = ["userTable/userTable",
            "login/login","organization/organization","office/office",
            "task/task","exam/exam","query/query","taskType/taskType","landing/landing",
            "uploadTask/uploadTask","sendTask/sendTask","orgOffice/orgOffice"];

pages.forEach(function(pathname) {
    var html = require('./html/' + pathname + '.html');
    var vm = require('./js/' + pathname + '.js');
    addState(pathname, vm, html);

    if(pathname == 'login/login'){
        avalon.router.add("/"+pathname, function(a) {
            root.needLogin = true;
            root.loginPage = getPage(this.path);
        })
    }
    avalon.router.add("/"+pathname, function(a) {
        root.currPath = this.path;
        root.currPage = getPage(this.path);
    })
});

var getLogin = function(pathname) {
    // body...
    var html = require('./html/' + pathname + '.html');
    var vm = require('./js/' + pathname + '.js');
    addState(pathname, vm, html);
}

avalon.history.start({
    root: "/"
});

avalon.router.navigate('/login/login', 2)//默认打开

// avalon.router.navigate('/login/login', 2);
// avalon.history.setHash('/bb/second');

// avalon.router.add('/login/login',function() {
//     // body...
//     // getLogin();
//     root.needLogin = true;
//     root.loginPath = this.path;
//     root.loginPage = getPage(this.path);
//     getLogin();
//     _alert(this.path);
// })


// avalon 扫页面
avalon.ready(function() {
    avalon.scan(document.body)
});


